<?php
/**
 * Created by PhpStorm.
 * User: guokunsheng
 * Date: 2020/2/1
 * Time: 12:36
 */

namespace app\api\controller\v15;

use app\api\controller\v2\Auth;
use app\common\cachemodel\IndexButton;
use app\common\lib\SensorsData;
use app\common\model\User;

/**
 * 青少年模式
 * Class YoungModel
 * @package app\api\controller\v15
 */
class YoungModel extends Auth
{
    /**
     * 青少年模式状态更新
     */
    public function change()
    {
        $password = input('password/s', '');
        if (!$password)
        {
            return show(config('code.error'), '请输入密码！');
        }

        $userModel = new User();
        if ($this->user['young_model'])
        {   // 已经开启 -> 关闭
            if ($password !== $this->user['young_pwd'])
            {
                // 因安卓密码未进行加密 所以现在两端不能相互解密   现新增两端相互解密逻辑
                if (($l1 = strlen($password)) !== ($l2 = strlen($this->user['young_pwd'])))
                {
                    if ($l1 > $l2)
                    {
                        $this->user['young_pwd'] = md5($this->user['young_pwd']);
                    } else
                    {
                        $password = md5($password);
                    }

                    if ($this->user['young_pwd'] !== $password)
                    {
                        return show(config('code.error'), '密码错误！');
                    }
                } else
                {
                    return show(config('code.error'), '密码错误！');
                }
            }
            $userModel->updateUserinfo(['id' => $this->user['id']], ['young_pwd' => '']);
            $status = 2;
        } else
        {  // 未开启   -> 开启
            $userModel->updateUserinfo(['id' => $this->user['id']], ['young_pwd' => $password]);
            $status = 1;
        }

        SensorsData::track($this->user['id'], true, 'YoungMode', [
            'handle_name' => $status === 1 ? '开启' : '关闭',
        ]);

        return show(config('code.success'), '更新成功', ['status' => $status]);
    }

    /**
     * 获取青少年状态
     */
    public function getStatus()
    {
        $type = input('btn_type/s', '');
        $needAuth = null;
        $isYoung = $this->user['young_model'];
        if ($type === 'lucky')
        {
            $needAuth = 3;
        } elseif ($type)
        {
            $needAuth = (new IndexButton())->getIndexButtonYoungLink(['ver' => $this->headers['version'], 'app_type' => $this->headers['app-type']], $type, $isYoung);
        }

        return show(config('code.success'), '请求成功', [
            'status' => $isYoung ? 1 : 2,
            'need_auth' => $needAuth
        ]);

    }
}
